<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="规格名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规格名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品" prop="goods_id">
        <el-select v-model="queryParams.goods_id" placeholder="请选择商品" clearable style="width: 240px" filterable>
          <el-option
            v-for="option in goodsOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="specList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="规格名称" prop="name" min-width="150" show-overflow-tooltip />
      <el-table-column label="商品" prop="goods_id" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ getGoodsName(scope.row.goods_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="price" width="120" align="center">
        <template slot-scope="scope">
          <span>¥{{ scope.row.price || '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="stock" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.stock || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重量" prop="weight" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.weight || '0' }}g</span>
        </template>
      </el-table-column>
      <el-table-column label="规格单位" prop="uint" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.uint || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否默认" prop="is_default" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_default ? 'success' : 'info'">{{ scope.row.is_default ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at ? parseTime(scope.row.created_at) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item label="商品" prop="goods_id">
          <el-select
            v-model="form.goods_id"
            placeholder="请选择商品"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="option in goodsOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :precision="2"
            :min="0"
            :step="0.01"
            placeholder="请输入价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            :step="1"
            placeholder="请输入库存"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品重量" prop="weight">
          <el-input-number
            v-model="form.weight"
            :precision="2"
            :min="0"
            :step="0.01"
            placeholder="请输入商品重量(单位:g)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="规格单位" prop="uint">
          <el-input-number
            v-model="form.uint"
            :min="0"
            :step="1"
            placeholder="请输入规格单位"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否默认" prop="is_default">
          <el-radio-group v-model="form.is_default">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="option in statusOptions" :key="option.value" :label="option.value">{{ option.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodSpecList, addGoodSpec, updateGoodSpec, getGoodsList } from '@/api/api'

export default {
  name: 'Spec',
  data() {
    return {
      loading: false,
      submitLoading: false,
      showSearch: true,
      specList: [],
      goodsOptions: [],
      goodsMap: {},
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 2 }
      ],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      open: false,
      queryParams: {
        page: 1,
        pageSize: 10,
        name: undefined,
        goods_id: undefined,
        status: undefined
      },
      form: {
        id: undefined,
        name: '',
        goods_id: undefined,
        status: 1,
        stock: 0,
        weight: 0,
        price: 0,
        is_default: false,
        uint: 0
      },
      rules: {
        name: [
          { required: true, message: '规格名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度需在 1 到 100 个字符', trigger: 'blur' }
        ],
        goods_id: [
          { required: true, message: '请选择商品', trigger: 'change' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '库存不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getGoodsOptions()
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      getGoodSpecList(this.queryParams)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.specList = list
          this.total = total || list.length
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    getGoodsOptions() {
      getGoodsList({})
        .then(res => {
          const { list } = this.normalizeResponse(res)
          this.goodsOptions = list.map(item => ({
            label: item.name || `商品${item.id}`,
            value: item.id
          }))
          this.goodsMap = {}
          list.forEach(item => {
            this.goodsMap[item.id] = item.name || `商品${item.id}`
          })
        })
    },
    getGoodsName(id) {
      return this.goodsMap[id] || '-'
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    reset() {
      this.form = {
        id: undefined,
        name: '',
        goods_id: undefined,
        status: 1,
        stock: 0,
        weight: 0,
        price: 0,
        is_default: false,
        uint: 0
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增规格'
    },
    handleUpdate(row) {
      const targetId = row?.id ?? this.ids[0]
      if (!targetId) {
        this.$modal.msgWarning('请选择要修改的规格')
        return
      }
      const record = this.specList.find(item => String(item.id) === String(targetId))
      if (!record) {
        this.$modal.msgWarning('未找到对应的规格数据')
        return
      }
      this.form = {
        id: record.id,
        name: record.name || '',
        goods_id: record.goods_id,
        status: record.status !== undefined && record.status !== null ? record.status : 1,
        stock: record.stock !== undefined && record.stock !== null ? record.stock : 0,
        weight: record.weight !== undefined && record.weight !== null ? record.weight : 0,
        price: record.price !== undefined && record.price !== null ? record.price : 0,
        is_default: record.is_default !== undefined && record.is_default !== null ? record.is_default : false,
        uint: record.uint !== undefined && record.uint !== null ? record.uint : 0
      }
      this.$nextTick(() => {
        if (this.$refs.form && this.$refs.form.clearValidate) {
          this.$refs.form.clearValidate()
        }
      })
      this.open = true
      this.title = '修改规格'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        this.submitLoading = true
        const payload = {
          ...this.form
        }
        const request = payload.id ? updateGoodSpec(payload) : addGoodSpec({ ...payload, id: undefined })
        request
          .then(() => {
            this.$modal.msgSuccess(payload.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = selection.length === 0
    },
    getStatusLabel(value) {
      const target = this.statusOptions.find(item => Number(item.value) === Number(value))
      return target ? target.label : '-'
    },
    getStatusTagType(value) {
      const match = Number(value)
      if (match === 1) {
        return 'success'
      }
      if (match === 2) {
        return 'danger'
      }
      return 'default'
    }
  }
}
</script>

<style scoped lang="scss">
</style>

